package ajax.quanxuan.sys.service.impl;

import ajax.quanxuan.sys.entity.Role;
import ajax.quanxuan.sys.dao.RoleMapper;
import ajax.quanxuan.sys.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author KazuGin
 * @since 2024-07-09
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Resource
    private RoleMapper roleMapper;

    @Override
    public boolean removeById(Serializable id) {
        //删除两张关系表的数据  分别是  sys_role_user   sys_role_permission
        //都是根据角色id删除的
        //调用删除角色用户关系表的方法
        roleMapper.deleteRoleUserByRoleId(id);
        //调用删除角色权限关系表的方法
        roleMapper.deleteRolePermissionByRoleId(id);
        return super.removeById(id);
    }

    @Override
    @Transactional
    public boolean saveRolePermission(int rid, String ids) {

        //先删除原来的数据
        if (rid != 0 && (ids != null && ids != "")){
            roleMapper.deleteRolePermissionByRoleId(rid);
            //再保存新的关系数据
            //拆分权限id字符串
            String[] pids = ids.split(",");
            if (pids.length > 0) {
                for (int i = 0; i < pids.length; i++) {

                    //调用保存角色权限关系的方法
                    roleMapper.insertRolePermission(rid, pids[i]);
                }
                return true;
            }
        }

        return false;

    }

    @Override
    public Set<Integer> findRoleParmissionByRoleId(Integer roleId) {
        return roleMapper.findRolePermissionByRoleId(roleId);
    }

    @Override
    public List<Role> list(Role role) {
        if (role.getPage()<0){
            role.setPage(1);
        }
        //获取最大数量
        Integer count =Integer.valueOf(roleMapper.count(role));
        //获取总页数   count/rows
        Integer size = count / role.getLimit();
        if (count % role.getLimit() > 0) {
            size++;
        }
        role.setSize(size);
        //如果当前页数大于总页数   则当前页等于总页数
        if (size == 0) {
            role.setPage(1);
        } else if (role.getPage() > role.getSize()) {
            role.setPage(size);
        }
        role.setCurrIndex((role.getPage() - 1) * role.getLimit());
        role.setPageSize(role.getLimit());
        return roleMapper.list(role);
    }

    @Override
    public Integer count(Role role) {
        return roleMapper.count(role);
    }

    @Override
    public List<Map<String,Object>> listAll(Role role) {
        return roleMapper.listAll(role);
    }

}
